import {Component} from '@angular/core';
import {AlertController, App, IonicPage, NavController} from 'ionic-angular';
import {PublicService} from "../../common/public.service";
import {HttpService} from "../../providers/HttpService";
import {RESETPWD_URL} from "../../providers/Constants";

/**
 * 修改密码
 */

@IonicPage()
@Component({
  selector: 'page-reset-password',
  templateUrl: 'reset-password.html',
})
export class ResetPasswordPage {

  public oldpwd: string;
  public newpwd: string;
  public confirmpwd: string;

  constructor(public navCtrl: NavController,
              public alertCtrl: AlertController,
              public app: App,
              public pub: PublicService,
              public http: HttpService) {
  }

  submitUpdate(oldpwd: HTMLInputElement, newpwd: HTMLInputElement, confirmpwd: HTMLInputElement) {
    if (oldpwd.value.length == 0) {
      this.pub.presentLoadingToast("请输入原密码");
    } else if (newpwd.value.length == 0) {
      this.pub.presentLoadingToast("请输入新密码");
    } else if (!this.isPasswd(newpwd.value)) {
      this.pub.presentLoadingToast("只能输入6-20个字母、数字、下划线");
    } else if (newpwd.value == oldpwd.value) {
      this.pub.presentLoadingToast("新密码和原密码不能相同");
    } else if (newpwd.value != confirmpwd.value) {
      this.pub.presentLoadingToast("新密码和确认密码不相同");
    } else {
      this.oldpwd = oldpwd.value;
      this.newpwd = newpwd.value;
      this.confirmpwd = confirmpwd.value;
      this.presentConfirm("提示", "确定修改密码吗？");
    }
  }


  //校验密码：只能输入6-20个字母、数字、下划线
  isPasswd(s) {
    var patrn = /^(\w){6,20}$/;
    if (!patrn.exec(s)) return false;
    return true;
  }

  presentConfirm(titleContext, content) {
    const alert = this.alertCtrl.create({
      title: titleContext,
      message: content,
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          handler: () => {
          }
        },
        {
          text: '确定',
          handler: () => {
            this.update();
          }
        }
      ]
    });
    alert.present();
  }

  update() {
    let params = {
      "sessionId": sessionStorage.getItem("session"),
      "reNewPwd": this.confirmpwd,
      "newPwd": this.newpwd,
      "oldPwd":this.oldpwd
    };

    this.http.get(SERVER_URL + RESETPWD_URL, "&", params, true).then(res => {
      if (res.success) {
        const alert1 = this.alertCtrl.create({
          title: '提示',
          message: "密码修改成功，请重新登录！",
          buttons: [
            {
              text: '确定',
              handler: () => {
                localStorage.removeItem("mpower-password");
                this.app.getRootNav().setRoot("LoginPage");
              }
            }
          ]
        });
        alert1.present();
      } else {
        this.pub.presentLoadingToast(res.msg);
        if (res.timeout) {
          setTimeout(() => {
            this.app.getRootNav().setRoot('LoginPage');
          }, 1500);
        }
      }
    });
  }
}
